#include "radardrv.h"

#define VHW_IIC_RADAR vIIC_3
#define IIC_ADDR_RADAR 0x28

static int32_t Radar_Read(uint8_t reg_addr, uint8_t *data, uint8_t len)
{
    if (Device_Write(VHW_IIC_RADAR, &reg_addr, 1, IIC_ADDR_RADAR) == 0)
    {
        return Device_Read(VHW_IIC_RADAR, data, len, IIC_ADDR_RADAR);
    }
    return 1;
}

static int32_t Radar_Write(uint8_t reg_addr, uint8_t *data, uint8_t len)
{
    uint8_t buffer[10] = {0};

    buffer[0] = reg_addr;
    memcpy(&buffer[1], data, len);
    return Device_Write(VHW_IIC_RADAR, buffer, len + 1, IIC_ADDR_RADAR);
}

static int32_t Radar_Write_Byte(uint8_t reg_addr, uint8_t data)
{
    return Radar_Write(reg_addr, (uint8_t *)&data, 1);
}

static int32_t Radar_Write_HalfWord(uint8_t reg_addr, uint16_t data)
{
    return Radar_Write(reg_addr, (uint8_t *)&data, 2);
}

static int32_t Radar_Write_Word(uint8_t reg_addr, uint32_t data)
{
    return Radar_Write(reg_addr, (uint8_t *)&data, 4);
}

/**
  * @brief  设置触发阈值
  * @note
  * @param  value：阈值
  * @return int32_t
  */
int32_t Radar_SetThreshold(uint16_t value)
{
    return Radar_Write_HalfWord(0x10, value);
}

int32_t Radar_Sleep(void)
{
    Radar_Write_Byte(0x5D, 0x46);
    Radar_Write_Byte(0x62, 0xaa);
    Radar_Write_Byte(0x51, 0x50);
    return 0;
}

int32_t Radar_Wake(void)
{
    Radar_Write_Byte(0x5D, 0x45);
    Radar_Write_Byte(0x62, 0x55);
    Radar_Write_Byte(0x51, 0xA0);
    return 0;
}

void Radar_Init(uint16_t threshold)
{
    Radar_Write_Byte(0x41, 0x01); //允许寄存器设置0x42指令
    // Radar_Write_Word(0x42, 2000); //设置触发保持时间（设置值大于2s）
    Radar_Write_Word(0x3D, 300); //设置触发保持时间（设置值可小于2s）
    Radar_Write_HalfWord(0x4E, 1000); //设置触发间隔保护时间
    Radar_Write_HalfWord(0x38, 1); //设置开机自检时间
    Radar_Write_Byte(0x67, 0xFB); //允许设置电流、阈值及设置电流
    Radar_Write_Byte(0x68, 0x68); //允许设置电流、阈值及设置电流
    Radar_Write_Byte(0x5C, 0x3B); //一级放大增益设为默认值
    Radar_Write_HalfWord(0x10, threshold); //设置触发阈值
    Radar_Write_Byte(0x66, 0x4A); //关闭光敏
    Radar_Write_Byte(0x55, 0x04); //配置GPIO输出下拉
    Radar_Write_Byte(0x00, 0x00); //复位
    Radar_Write_Byte(0x00, 0x01); //释放复位
    Device_DelayMs(5);
}
